package filter;


import javax.servlet.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;

public class CharacterEncodingFilter implements Filter {
    private String encoding ;
    @Override
    public void init(FilterConfig config) throws ServletException {
         encoding = config.getInitParameter("encoding") ;
         if(Objects.isNull(encoding) ){
             if(encoding.trim().length() < 0){
                 encoding = "UTF-8" ;
             }
         }
         if( !Charset.isSupported(encoding) ){
             this.encoding = "UTF-8" ;
         }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        request.setCharacterEncoding(this.encoding);
        response.setCharacterEncoding(this.encoding);
        System.out.println(this.encoding);
        System.out.println("经过编码过滤器了");
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
    }
}
